package com.ojoin.trade.t0loan_core.web.service.impl;

import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.ojoin.trade.common.constdef.IConstDef;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.FileUploadUtils;
import com.ojoin.trade.common.utils.Html2PDFAsianUtil;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.TimeUtils;
import com.ojoin.trade.common.utils.UUIDUtils;
import com.ojoin.trade.common.web.dao.BaseDao;
import com.ojoin.trade.common.web.service.TbUploadFileService;
import com.ojoin.trade.common.web.service.impl.BaseServiceImpl;
import com.ojoin.trade.common_core.web.domain.TbMerchantInfo;
import com.ojoin.trade.common_core.web.domain.TbMerchantuserFinaccount;
import com.ojoin.trade.common_core.web.service.AccountBaseService;
import com.ojoin.trade.common_core.web.service.MerchantUserBaseService;
import com.ojoin.trade.common_core.web.service.TbMerchantInfoBaseService;
import com.ojoin.trade.common_core.web.service.TbMerchantuserFinaccountService;
import com.ojoin.trade.common_core.web.service.impl.DataVersionValidationService;
import com.ojoin.trade.t0loan_core.web.dao.TbT0LoanLiveApplicationDao;
import com.ojoin.trade.t0loan_core.web.domain.T0LoanLiveUserHistoryTransTotalInfoVO;
import com.ojoin.trade.t0loan_core.web.domain.TbT0LoanFinalApplication;
import com.ojoin.trade.t0loan_core.web.domain.TbT0LoanLiveApplication;
import com.ojoin.trade.t0loan_core.web.domain.TbT0LoanLiveInfoVO;
import com.ojoin.trade.t0loan_core.web.domain.TbT0LoanTodoTaskVO;
import com.ojoin.trade.t0loan_core.web.service.T0LoanFinalBaseService;
import com.ojoin.trade.t0loan_core.web.service.T0LoanLiveBaseService;

/**
 * T+0贷款申请服务实现
 * 
 * @author guoting
 * 
 */
@Service
public class T0LoanLiveBaseServiceImpl extends
		BaseServiceImpl<TbT0LoanLiveApplication> implements
		T0LoanLiveBaseService {

	@Autowired
	private TbT0LoanLiveApplicationDao dao;

	@Autowired
	private MerchantUserBaseService userservice;
	
	@Autowired
	private TbMerchantInfoBaseService infoservice;
	
	@Autowired
	private AccountBaseService accountService;
	
	@Autowired
	private T0LoanFinalBaseService finalservice;
	
	@Autowired
	private TbMerchantuserFinaccountService userFinaccountService;
	
    @Autowired
    private TbUploadFileService uploadFileService;
    
	@Autowired
	private DataVersionValidationService validateService;
	
	/**
	 * 新增T+0贷款申请记录(T0000001)
	 */
	@Override
	public int insertT0LoanLiveInfo(int joinuserNo) throws BusinessException {
		LogUtils.getT0loanLog().info("新增T+0贷款申请记录. joinuserNo->" + joinuserNo);
		
		//判断是否已存在该用户的T+0申请记录（非申请被拒和非申请终止），存在则直接返回id
		List<TbT0LoanLiveApplication> livelist = queryT0LoanLiveInfoByJoinUserID(joinuserNo);
		if (livelist != null && livelist.size() > 0) {
			for(TbT0LoanLiveApplication livevo : livelist) {
				if (livevo.getLoanstatus() != IConstDef.LOANLIVETYPE_REFUSE && 
					livevo.getLoanstatus() != IConstDef.LOANLIVETYPE_STOPED)
					LogUtils.getT0loanLog().info("已存在joinuserno->" + joinuserNo + "用户的T+0贷款申请记录，状态->" + livevo.getLoanstatus());
				
				return livevo.getId();
			}
		}
		
		TbT0LoanLiveApplication livevo = new TbT0LoanLiveApplication();

		// livevo设值
		livevo.setIdOfTbMerchantUser(joinuserNo);
		livevo.setLoanstatus(IConstDef.LOANLIVETYPE_DOING);
		livevo.setOperationType(IConstDef.T0_LOAN_CREDIT);

		this.getBaseDao().insert(livevo);
		return livevo.getId();

	}

	/**
	 * 新增T+1贷款申请记录
	 */
	@Override
	public int insertTxLoanLiveInfo(int joinuserNo, String operation_type) throws BusinessException {
		LogUtils.getT0loanLog().info("新增T+1贷款申请记录. joinuserNo->" + joinuserNo);
		
		//判断是否已存在该用户的T+1申请记录（非申请被拒和非申请终止），存在则直接返回id
		List<TbT0LoanLiveApplication> livelist = queryT1LoanLiveInfoByJoinUserID(joinuserNo);
		if (livelist != null && livelist.size() > 0) {
			for(TbT0LoanLiveApplication livevo : livelist) {
				return livevo.getId();
			}
		}
		
		//同步商户实名信息
		infoservice.syncRealName(joinuserNo);
		
		TbT0LoanLiveApplication livevo = new TbT0LoanLiveApplication();

		// livevo设值
		livevo.setIdOfTbMerchantUser(joinuserNo);
		livevo.setLoanstatus(IConstDef.T1_LOANLIVETYPE_DOING);
		livevo.setOperationType(operation_type);

		this.getBaseDao().insert(livevo);
		return livevo.getId();

	}
	
	/**
	 * 根据九盈用户id查询用户的T+0贷款申请记录(T0000002)
	 */
	@Override
	public List<TbT0LoanLiveApplication> queryT0LoanLiveInfoByJoinUserID(
			int joinuserid) throws BusinessException {
		LogUtils.getT0loanLog().info("根据九盈用户id查询用户的T+0贷款申请记录. joinuserid->" + joinuserid);
		
		List<TbT0LoanLiveApplication> selectList = ((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).queryT0LoanLiveInfoByJoinUserID(joinuserid);
		if (selectList == null || selectList.size() == 0)
			return null;

		return selectList;
	}

	/**
	 * 根据九盈用户id查询用户的T+1贷款申请记录
	 */
	@Override
	public List<TbT0LoanLiveApplication> queryT1LoanLiveInfoByJoinUserID(
			int joinuserid) throws BusinessException {
		LogUtils.getT0loanLog().info("根据九盈用户id查询用户的T+1贷款申请记录. joinuserid->" + joinuserid);
		
		List<TbT0LoanLiveApplication> selectList = ((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).queryT1LoanLiveInfoByJoinUserID(joinuserid);
		if (selectList == null || selectList.size() == 0)
			return null;

		return selectList;
	}
	
	/**
	 * 根据九盈用户id查询用户的最近一次T+0贷款申请记录(T0000025)
	 */
	@Override
	public TbT0LoanLiveApplication queryNewlyT0LoanLiveInfoByJoinUserID(
			int joinuserid) throws BusinessException {
		LogUtils.getT0loanLog().info("根据九盈用户id查询用户的最近一次T+0贷款申请记录. joinuserid->" + joinuserid);
		
		return ((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).queryNewlyT0LoanLiveInfoByJoinUserID(joinuserid);
	}
	
	/**
	 * 根据九盈用户id查询用户的最近一次T+0贷款申请记录(T0000025)
	 */
	@Override
	public TbT0LoanLiveApplication queryNewlyTxLoanLiveInfoByJoinUserID(
			int joinuserid, String operation_type) throws BusinessException {
		LogUtils.getT0loanLog().info("根据九盈用户id查询用户的最近一次T+1贷款申请记录. joinuserid->" + joinuserid + " operation_type->" + operation_type);
		
		return ((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).queryNewlyTxLoanLiveInfoByJoinUserID(joinuserid, operation_type);
	}
	
	/**
	 * 查询指定贷款状态的所有九盈用户T+0贷款业务申请记录 (T0000003)
	 */
	@Override
	public List<TbT0LoanLiveInfoVO> queryAllT0LoanLiveInfoByStatus(
			Integer loanstatus, Pageable page) throws BusinessException {
		LogUtils.getT0loanLog().info("查询指定贷款状态的所有九盈用户T+0贷款业务申请记录. loanstatus->" + loanstatus + ", pageno->" +page.getPageNumber() + ", pagesize->" + page.getPageSize());
		
		List<TbT0LoanLiveInfoVO> infolist = ((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).queryAllT0LoanLiveInfoByStatus(loanstatus, page);
		if (infolist == null || infolist.size() == 0)
			return null;

		return infolist;
	}

	/**
	 * 查询申请中的所有九盈用户T+1贷款业务申请记录
	 */
	@Override
	public List<TbT0LoanLiveInfoVO> queryAllTxLoanLiveInfoByApplying(
			Pageable page, String operation_type) throws BusinessException {
		LogUtils.getT0loanLog().info("查询申请中的所有九盈用户T+1贷款业务申请记录. " + "pageno->" +page.getPageNumber() + ", pagesize->" + page.getPageSize());
		
		List<TbT0LoanLiveInfoVO> infolist = ((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).queryAllTxLoanLiveInfoByApplying(page, operation_type);
		if (infolist == null || infolist.size() == 0)
			return null;

		return infolist;
	}
	
	@Override
	protected BaseDao<TbT0LoanLiveApplication> getBaseDao() {
		return dao;
	}

	@Override
	public int updateT0LoanLiveInfoByLiveIDsAndStatus(int[] liveids,
			int loanstatus) throws BusinessException {
		LogUtils.getT0loanLog().info("修改指定审计记录的T+0贷款申请状态. liveids->" + CommonUtils.getStrByIDs(liveids) + ", loanstatus->" + loanstatus);
		
		return ((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).updateT0LoanLiveInfoByLiveIDsAndStatus(liveids, loanstatus);

	}
	
	@Override
	public int updateTxLoanLiveInfoByLiveIDsAndStatus(String operatetype, int[] liveids, int idOfTbMerchantUserOfCreditor,
			int loanstatus) throws BusinessException {
		LogUtils.getT0loanLog().info("修改指定审计记录的T+1贷款申请状态. liveids->" + CommonUtils.getStrByIDs(liveids) + ", loanstatus->" + loanstatus);
		
		return ((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).updateTxLoanLiveInfoByLiveIDsAndStatus(operatetype, liveids, idOfTbMerchantUserOfCreditor, loanstatus);

	}

	@Override
	public List<T0LoanLiveUserHistoryTransTotalInfoVO> queryT0LoanLiveUserHistoryTransTotalInfoList(Pageable page)
			throws BusinessException {
		LogUtils.getT0loanLog().info("查询申请T+0贷款审核通过的九盈用户的当日前30日历史交易金额合计列表. pageno->" + page.getPageNumber() + ", pagesize->" + page.getPageSize());
		
		List<T0LoanLiveUserHistoryTransTotalInfoVO> infolist = ((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).queryT0LoanLiveUserHistoryTransTotalInfoList(page);

		return infolist;
	}

	@Override
	public int updateT0LoanLiveInfoFeeAndRatioByLiveID(int liveid, String fee,
			String ratio, String expected_loan_time, int creditorid) throws BusinessException {
		LogUtils.getT0loanLog().info("修改T+0贷款申请记录的设定手续费和利率，并更新状态为2. creditorid->" + creditorid + ", liveid->" + liveid + ", fee->" + fee + ", ratio->" + ratio);
		
		return ((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).updateT0LoanLiveInfoFeeAndRatioByLiveID(liveid, fee, ratio, expected_loan_time, creditorid);
	}

	/**
	 * 修改T+0贷款申请记录的授信额度、生成相关文件，并更新状态为3 (T0000035) 
	 * 说明： 
	 * 1)、生成保理合同pdf文件，填充相关内容 
	 * 2)、生成账户变更申请表文件，填充相关内容
	 * 3)、更新授信额度及保理合同、账户变更申请表文件路径及状态为3
	 */
	@Override
	public int updateT0LoanLiveInfoLimitByLiveID(int liveid, int joinuserid,
			String rm_daily_threshold, String rm_single_threshold, String qryprintscreen, String filePath) throws BusinessException {
		LogUtils.getT0loanLog().info("修改T+0贷款申请记录的授信额度、生成相关文件，并更新状态为3. " +
				"liveid->" + liveid + ", " +
				"joinuserid->" + joinuserid + ", " +
				"rm_daily_threshold->" + rm_daily_threshold + ", " +
				"rm_single_threshold->" + rm_single_threshold +
				"qryprintscreen->" + qryprintscreen);
		
		String mhtno = userservice.queryPayUserByJoinUserID(joinuserid);
		//查询结算户账号
//		String finAccBankNo = accountService.queryFinanceAccountBankNo(mhtno);
		String finAccBankNo = "testbankno";
				
		//1)、生成保理合同pdf文件，填充相关内容 
		TbT0LoanLiveApplication livevo = this.queryById(liveid);
		String contractfilepath = generateContractFile(joinuserid, livevo.getIdOfTbMerchantUserOfCreditor(), mhtno, finAccBankNo, livevo.getFee(), livevo.getRatio(), 
				livevo.getExpectedLoanTime(), rm_daily_threshold, rm_single_threshold,filePath);
		//取相对路径
		contractfilepath=IConstDef.contractGenFileDir+File.separator+FileUploadUtils.getFileNameFromPath(contractfilepath);
		
		//2)、生成账户变更申请表文件，填充相关内容
		String accchangeapplyfilepath = generateAccountChangeApplyFile(mhtno, finAccBankNo, filePath);
		//取相对路径
		accchangeapplyfilepath=IConstDef.contractGenFileDir+File.separator+FileUploadUtils.getFileNameFromPath(accchangeapplyfilepath);
				
		//更新授信凭证上传文件状态为已提交
		uploadFileService.updateStatusById(CommonUtils.getInt(qryprintscreen), IConstDef.UPLOADSTATUS_COMMITED);

		//3)、更新授信额度及保理合同、账户变更申请表文件路径及状态为3
		return ((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).updateT0LoanLiveInfoLimitByLiveID(liveid, joinuserid, 
						rm_daily_threshold, rm_single_threshold, qryprintscreen, 
						contractfilepath, accchangeapplyfilepath);		
	}

	//根据相关参数生成账户变更申请表
	public String generateAccountChangeApplyFile(String mhtno, String finAccBankNo, String targetPDFFileFolder) throws BusinessException {
		LogUtils.getT0loanLog().info("生成账户变更申请表，mhtno->" + mhtno);
		
		TbMerchantInfo uservo = infoservice.queryInfoByMhtno(mhtno);
		
		//此处的分隔符必须使用/,不可使用File.separator，否则取到的path为空
		InputStream templatePDFfilePath = this.getClass().getResourceAsStream("/t0load/accchange.html");
    	String accountChangeApplyFilePath = generateAccChangeFileByMhtno(uservo, finAccBankNo, targetPDFFileFolder, templatePDFfilePath);
    	
		LogUtils.getT0loanLog().info("生成账户变更申请表，文件路径->" + accountChangeApplyFilePath);
		return accountChangeApplyFilePath;
	}

	/**
	 * 生成指定商户的账户变更申请表pdf文件
	 * 
	 * @param mhtvo
	 * @return
	 */
	private String generateAccChangeFileByMhtno(TbMerchantInfo mhtvo,
			String finAccBankNo, String targetPDFFileFolder,
			InputStream templatefilePath) throws BusinessException {
		HashMap<String, String> replaceMap = new HashMap<String, String>();
		replaceMap.put("mhtname", mhtvo.getMchName());
		replaceMap.put("mhtno", mhtvo.getMhtNo());
		replaceMap.put("generatedate", TimeUtils.getCurDateInFile());

		replaceMap.put("accno", finAccBankNo);

		String filePrefix = "t0accchange";
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
				"yyyyMMddHHmmss");
		String targetPDFFilename = filePrefix + "_"
				+ simpleDateFormat.format(new Date()) + "_"
				+ UUIDUtils.create();

		return new Html2PDFAsianUtil().generatePDFFileByMhtno(replaceMap, targetPDFFileFolder,
				targetPDFFilename, templatefilePath, filePrefix, null);
	}
	
	//根据相关参数生成保理合同
	private String generateContractFile(int joinuserid, int creditorid, 
			String mhtno, String finAccBankNo, String fee, String ratio,
			String expected_loan_time, String rm_daily_threshold,
			String rm_single_threshold,String targetFilePath) throws BusinessException {
		
		LogUtils.getT0loanLog().info("生成保理合同，" +
				"joinuserid->" + joinuserid + ", " +
				"mhtno->" + mhtno + ", " +
				"fee" + fee + ", " +
				"ratio->" + ratio + ", " +
				"expected_loan_time->" + expected_loan_time + ", " +
				"rm_daily_threshold->" + rm_daily_threshold + ", " +
				"rm_single_threshold->" + fee);
		
		TbMerchantInfo uservo = infoservice.queryInfoByMhtno(mhtno);
		TbMerchantInfo creditor = infoservice.queryInfoByJoinId(creditorid);
		
		//此处的分隔符必须使用/,不可使用File.separator，否则取到的path为空
		InputStream templatePDFfilePath = this.getClass().getResourceAsStream("/t0load/t0contract.html");
    	String contractFilePath = generateContractFileByMhtno(joinuserid, creditorid, uservo, creditor, finAccBankNo, targetFilePath, templatePDFfilePath, fee);
    	
		LogUtils.getT0loanLog().info("生成保理合同，文件路径->" + contractFilePath);
		return contractFilePath;
	}

	/**
	 * 生成指定商户的保理合同pdf文件
	 * 
	 * @param mhtvo
	 * @return
	 */
	public String generateContractFileByMhtno(int joinuserid, int creditorid, 
			TbMerchantInfo mhtvo, TbMerchantInfo creditor, String finAccBankNo,
			String targetPDFFileFolder, InputStream templatefilePath, String fee)
			throws BusinessException {
		HashMap<String, String> replaceMap = new HashMap<String, String>();
		replaceMap.put("#mhtname#", mhtvo.getMchName());
		replaceMap.put("#name#", mhtvo.getName());
		replaceMap.put("#mobile#", mhtvo.getMobile());
		
		replaceMap.put("#creditorMchName#", creditor.getMchName());
		replaceMap.put("#creditorAddress#", creditor.getAddress());
		replaceMap.put("#creditorName#", creditor.getName());
		
		String contactno = getContractNO(joinuserid);
		replaceMap.put("#contractno#", contactno);

		replaceMap.put("finAccBankNo", finAccBankNo);

		String filePrefix = "t0load";
		String targetPDFFilename = filePrefix + "_" + UUIDUtils.create() + "_"
				+ contactno;
		return new Html2PDFAsianUtil().generatePDFFileByMhtno(replaceMap, targetPDFFileFolder,
				targetPDFFilename, templatefilePath, filePrefix, contactno);
	}
	
	private String getContractNO(int joinuserid) {
		StringBuffer str = new StringBuffer();
		str.append(IConstDef.T0LOANPREFIX);
		str.append(StringUtils.right("00000" + joinuserid, 5));
		str.append(IConstDef.T0LOANSUFFIX);

		return str.toString();
	}
	
	@Override
	public String[] queryT0LoanLiveContractFileByJoinuserid(int joinuserid)
			throws BusinessException {
		LogUtils.getT0loanLog().info("查询指定九盈用户申请T+0贷款记录状态为3的信息，获取生成的保理合同和账户变更申请表. joinuserid->" + joinuserid);
		
		return ((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).queryT0LoanLiveContractFileByJoinuserid(joinuserid);
	}

	@Override
	public int uploadT0LoanUserCommitFileByLiveID(int liveid, String userchangefilepath) throws BusinessException {
		LogUtils.getT0loanLog().info("上传用户盖章后的账户变更申请表，修改T+0贷款申请记录的状态为4. liveid->" + liveid + ", userchangefilepath->" + userchangefilepath);
		
		return ((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).uploadT0LoanUserCommitFileByLiveID(liveid, userchangefilepath);
	}

	@Override
	public int updateT0LoanLiveInfoUserCommitPass(int liveid) throws BusinessException {
		LogUtils.getT0loanLog().info("更新T+0贷款申请记录的状态为5(用户提交的账户变更申请表审核通过). liveid->" + liveid);
		
		((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).updateT0LoanLiveInfoByLiveIDsAndStatus(new int[] {liveid}, IConstDef.LOANLIVETYPE_USERCOMMITPASS);
		return 0;
	}

	@Override
	public int updateT0LoanLiveInfoAccChangePassAndCreateFinalInfo(int liveid, String materials)
			throws BusinessException {
		
		LogUtils.getT0loanLog().info("更新T+0贷款申请记录的状态为7(放款初审，结算账户已变更). liveid->" + liveid);
		
		((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).uploadT0LoanAccountChangeFileByLiveID(liveid, materials);
		
		TbT0LoanLiveApplication livevo = this.queryById(liveid);
		
		//查询是否存在finalvo，如存在删除后再新增
		TbT0LoanFinalApplication existsFinalVO = finalservice.queryTxLoanFinalInfoByJoinUserID(livevo.getIdOfTbMerchantUser());
		if (existsFinalVO != null) {
			LogUtils.getT0loanLog().info("删除已存在的贷款申请最终记录. finalvoid->" + existsFinalVO.getId());
			finalservice.deleteById(existsFinalVO.getId());
		}
		
		//新增贷款申请最终记录, 设置所有字段
		LogUtils.getT0loanLog().info("新增贷款申请最终记录.");
		TbT0LoanFinalApplication finalvo = new TbT0LoanFinalApplication();
		finalvo.setIdOfTbMerchantUser(livevo.getIdOfTbMerchantUser());
		finalvo.setMaterials(livevo.getMaterials());
		finalvo.setFee(livevo.getFee());
		finalvo.setRatio(livevo.getRatio());
		finalvo.setExpectedLoanTime(livevo.getExpectedLoanTime());
		finalvo.setRmDailyThreshold(livevo.getRmDailyThreshold());
		finalvo.setRmSingleThreshold(livevo.getRmSingleThreshold());
		finalvo.setContractfilepath(livevo.getContractfilepath());
		finalvo.setAccchangeapplyfilepath(livevo.getAccchangeapplyfilepath());
		finalvo.setUsercommitapplyfilepath(livevo.getUsercommitapplyfilepath());
		finalvo.setQryprintscreen(livevo.getQryprintscreen());
		finalvo.setIdOfTbMerchantUserOfCreditor(livevo.getIdOfTbMerchantUserOfCreditor());
		finalvo.setOperationType(livevo.getOperationType());
		finalservice.insert(finalvo);
		
		//更新账户变更申请表文件状态为已提交
		uploadFileService.updateStatusById(CommonUtils.getInt(livevo.getMaterials()), IConstDef.UPLOADSTATUS_COMMITED);

		return finalvo.getId();
	}

	@Override
	public int updateTxLoanLiveInfoAndCreateFinanceAccount(String operatetype, int liveid, int idOfTbMerchantUserOfCreditor, String pagets)
			throws BusinessException {
		// 操作数据版本校验
		TbT0LoanLiveApplication validateVO = new TbT0LoanLiveApplication();
		validateVO.setId(liveid);
		validateService.validateVO(validateVO, pagets);
				
		((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).updateTxLoanLiveInfoByLiveIDsAndStatus(operatetype, new int[] {liveid}, idOfTbMerchantUserOfCreditor, IConstDef.T1_LOANLIVETYPE_APPROVED);
		LogUtils.getT0loanLog().info("已更新Tx贷款申请记录的状态为2(已开通金融户). liveid->" + liveid);
		
		return liveid;
	}
	
	@Override
	public int updateTxLoanLiveInfoAndSetFinanceAccount(String operatetype, int liveid, String financeAccount, String pagets)
			throws BusinessException {
		// 操作数据版本校验
		TbT0LoanLiveApplication validateVO = new TbT0LoanLiveApplication();
		validateVO.setId(liveid);
		validateService.validateVO(validateVO, pagets);
		
		TbT0LoanLiveApplication livevo = this.queryById(liveid);

		int businesstype = 0;
		if (IConstDef.T1_LOAN_CREDIT.equals(operatetype) || 
			IConstDef.D1_LOAN_CREDIT.equals(operatetype) ||
			IConstDef.T0_LOAN_CREDIT.equals(operatetype)) {
			businesstype = IConstDef.TYPE_TXLOAN;
		}
		TbMerchantuserFinaccount accountvo = new TbMerchantuserFinaccount();
		accountvo.setBusinessType(businesstype);
		accountvo.setFinanceAccount(financeAccount);
		accountvo.setAccountType(IConstDef.CMBC_TYPE);
		accountvo.setIdOfTbMerchantUser(livevo.getIdOfTbMerchantUser());
		userFinaccountService.insertTbMerchantuserFinaccount(accountvo);
		LogUtils.getT0loanLog().info("已设置金融户. joinuserid->" + livevo.getIdOfTbMerchantUser() + "financeAccount->" + financeAccount);
		
		((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).updateTxLoanLiveInfoByLiveIDsAndStatus(operatetype, 
						new int[] {liveid}, livevo.getIdOfTbMerchantUserOfCreditor(), 
						IConstDef.T1_LOANLIVETYPE_ACCOUNTENABLED);
		LogUtils.getT0loanLog().info("已更新" + operatetype +"贷款申请记录的状态为3(申请成功，已设置金融户). liveid->" + liveid);
		
		//查询是否存在finalvo，如存在删除后再新增
		TbT0LoanFinalApplication existsFinalVO = finalservice.queryTxLoanFinalInfoByJoinUserIDAndType(livevo.getIdOfTbMerchantUser(), operatetype);
		if (existsFinalVO != null) {
			LogUtils.getT0loanLog().info("已删除已存在的" + operatetype +"贷款申请最终记录. finalvoid->" + existsFinalVO.getId());
			finalservice.deleteById(existsFinalVO.getId());
		}
		
		//新增贷款申请最终记录, 设置所有字段
		TbT0LoanFinalApplication finalvo = new TbT0LoanFinalApplication();
		finalvo.setIdOfTbMerchantUser(livevo.getIdOfTbMerchantUser());
		finalvo.setOperationType(operatetype);
		finalvo.setIdOfTbMerchantUserOfCreditor(livevo.getIdOfTbMerchantUserOfCreditor());
		finalservice.insert(finalvo);
		LogUtils.getT0loanLog().info("已新增" + operatetype +"贷款申请最终记录.");
		
		return finalvo.getId();
	}
	
	@Override
	public int updateT0LoanLiveInfoUserCommitNoPassByLiveID(int liveid,
			String memo) throws BusinessException {
		LogUtils.getT0loanLog().info("审核用户提交的账户变更申请表不通过，提交不通过原因并更新状态为6. liveid->" + liveid + ", memo->" + memo);
		
		((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).updateT0LoanLiveInfoUserCommitNoPassByLiveID(liveid, memo);
		return 0;
	}

	@Override
	public int updateT0LoanLiveInfoApplyNoPassByLiveID(int liveid,
			String memo) throws BusinessException {
		LogUtils.getT0loanLog().info("审核用户T+0业务申请不通过，提交不通过原因并更新状态为-1. liveid->" + liveid + ", memo->" + memo);
		
		((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).updateTxLoanLiveInfoApplyNoPassByLiveID(IConstDef.T0_LOAN_CREDIT, liveid, memo);
		return 0;
	}

	@Override
	public int updateTxLoanLiveInfoApplyNoPassByLiveID(String operatetype, int liveid,
			String memo, String pagets) throws BusinessException {
		// 操作数据版本校验
		TbT0LoanLiveApplication validateVO = new TbT0LoanLiveApplication();
		validateVO.setId(liveid);
		validateService.validateVO(validateVO, pagets);
		
		LogUtils.getT0loanLog().info("审核用户Tx业务申请不通过，提交不通过原因并更新状态为-1. operatetype->" + operatetype + ", liveid->" + liveid + ", memo->" + memo);
		
		((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).updateTxLoanLiveInfoApplyNoPassByLiveID(operatetype, liveid, memo);
		return 0;
	}
	
	@Override
	public List<TbT0LoanTodoTaskVO> queryAdminUserTodoTaskList()
			throws BusinessException {
		LogUtils.getT0loanLog().info("查询后台管理员代办任务列表");
		
		List<TbT0LoanTodoTaskVO> selectList = ((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).queryAdminUserTodoTaskList();
		if (selectList == null || selectList.size() == 0)
			return null;

		return selectList;
	}

	@Override
	public List<TbT0LoanTodoTaskVO> queryOperatorTodoTaskList()
			throws BusinessException {
		LogUtils.getT0loanLog().info("查询保理员代办任务列表");
		
		List<TbT0LoanTodoTaskVO> selectList = ((TbT0LoanLiveApplicationDao) this
				.getBaseDao()).queryOperatorTodoTaskList();
		if (selectList == null || selectList.size() == 0)
			return null;

		return selectList;
	}
}
